package main

import (
	"fmt"
	"regexp"
)

func main() {
	pattern := "[0-9]+"

	re, err := regexp.Compile(pattern)
	if err != nil {
		fmt.Println("Error compiling regex", err)
	}

	// 测试正则是否匹配
	str := "The 12 monkeys ate 48 bananas"
	if re.MatchString(str) {
		fmt.Println("Yes, matched a number")
	} else {
		fmt.Println("No, no match")
	}

	// 返回匹配结果
	result := re.FindString(str)
	fmt.Println("Number matched:", result)

	// 返回多个匹配结果, 指定 -1 返回所有
	results := re.FindAllString(str, 2)
	for i, v := range results {
		fmt.Printf("Match %d: %s\n", i, v)
	}

	// 替换
	resultsOfReplace := re.ReplaceAllString(str, "xx")
	fmt.Println("resultsOfReplace:", resultsOfReplace)

	caseInsensitive()
	submatches()
	// 特殊转义符
	escapingSpecialCharacters()
}

func caseInsensitive() {
	// 用来检测一个字符串是否以"t"开头。通常可以用来过滤或搜索以"t"开头的字符串并忽略t大小写, 备注：(?i)即匹配时不区分大小写
	ptn := `(?i)^t.`
	str := "Tox be or not to be"

	re, err := regexp.Compile(ptn)
	if err != nil {
		fmt.Println("Error compiling regex", err)
	}

	// match string
	result := re.FindString(str)
	fmt.Println("result is:", result)
}

func submatches() {
	str1 := "Hello @world@ Match"
	sub_re, _ := regexp.Compile("@(.*)@")

	m := sub_re.FindStringSubmatch(str1)
	fmt.Println(m)
	// FindStringSubmatch returns [@world@ world]
	// so to just get the submatch you would use
	if len(m) > 1 {
		fmt.Println(m[1]) // submatch
	}
}

func escapingSpecialCharacters() {
	str2 := "A [word] here and [there]"
	esc_pattern := `\[(.*?)\]`
	esc_re, _ := regexp.Compile(esc_pattern)

	// this will only find the first
	fmt.Println(esc_re.FindStringSubmatch(str2))

	// use FindAll with second parameter for # of matches -1 = all
	fmt.Println(esc_re.FindAllStringSubmatch(str2, -1))
}
